package com.yuke.cloud.service.omc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.omc.dto.*;
import com.yuke.cloud.service.omc.entity.OdsTeam;
import com.yuke.cloud.service.omc.entity.OdsTeamGoods;
import com.yuke.cloud.service.omc.entity.OdsTeamIntent;
import com.yuke.cloud.service.omc.redis.RedisCacheTemplate;
import com.yuke.cloud.service.omc.service.OdsTeamGoodsService;
import com.yuke.cloud.service.omc.service.OdsTeamIntentService;
import com.yuke.cloud.service.omc.service.OdsTeamService;
import com.yuke.cloud.service.omc.utils.SequenceUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* Created by zn on 2020/09/26.
*/
@Api(value = "WEB - OdsTeamController", tags = "处理OdsTeam相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/ods/team")
public class OdsTeamController extends BaseController {
    @Resource
    private OdsTeamService odsTeamService;
    @Resource
    private OdsTeamIntentController odsTeamIntentController;
    @Resource
    private OdsTeamIntentService odsTeamIntentService;
    @Resource
    private OdsTeamGoodsService odsTeamGoodsService;
    @Autowired
    private RedisCacheTemplate redisCacheTemplate;

    private static final String SERIAL_NUM = "redis:serialTeamNumber:";


    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "odsTeam", value = "该数据记录的POJO") @RequestBody OdsTeam odsTeam) {
        odsTeam.setTeamId(generateId());
        String timeStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = SERIAL_NUM + timeStr;
        long incr = redisCacheTemplate.incr(key, 1, 86400);
        //移位运算符<<，左移几位相当于乘以2的几次方, 1 << 2 = 4
        String code = SequenceUtils.getSequence(incr, 1 << 2);
        odsTeam.setTeamNo(timeStr + code);
        odsTeamService.saveTeamInfo(odsTeam);

        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        odsTeamService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "odsTeam", value = "需要修改的内容") @RequestBody OdsTeam odsTeam) {
        odsTeamService.update(odsTeam);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<OdsTeam> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        OdsTeam odsTeam = odsTeamService.findById(id);
        return WrapMapper.ok(odsTeam);
    }

    @PostMapping("/selectTeamList")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<OdsTeamDto>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                              @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                              @RequestBody OdsTeamDto odsTeamDto) {
        PageHelper.startPage(page, size);
        List<OdsTeamDto> list = odsTeamService.getTeamInfo(odsTeamDto);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 获取历史开团记录，每个团的商品列表
     *
     * @param page
     * @param size
     * @param odsTeamDto
     * @return
     */
    @PostMapping("/selectTeamRecordList")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<OdsTeamRecordDto>> selectTeamRecordList(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                    @RequestBody OdsTeamDto odsTeamDto) {
        PageHelper.startPage(page, size);
        List<OdsTeamRecordDto> list = odsTeamService.selectTeamRecordList(odsTeamDto);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 查找对应拼单信息，storageId，teamType，teamStatus
     * 返回拼单信息和拼单订单信息
     *
     * @param odsTeamInfoDto
     * @return
     */
    @PostMapping("/selectTeamInfo")
    @ApiOperation(httpMethod = "POST", value = "获取所有记录")
    public Wrapper selectTeamInfo(OdsTeamInfoDto odsTeamInfoDto) {
        List<OdsTeamInfoDto> list = odsTeamService.selectTeamInfo(odsTeamInfoDto);
        if (list != null && list.size() > 0) {
            odsTeamInfoDto = list.get(0);
            OdsTeamIntentDto odsTeamIntentDto = new OdsTeamIntentDto();
            odsTeamIntentDto.setTeamId(odsTeamInfoDto.getTeamId());
            List<OdsTeamIntentDto> odsTeamIntentDtoList = odsTeamIntentService.selectTeamIntentByCondition(odsTeamIntentDto);
            odsTeamInfoDto.setOdsTeamIntentDtoList(odsTeamIntentDtoList);
            return WrapMapper.ok(odsTeamInfoDto);
        }
        return WrapMapper.error("没有找到对应信息！");
    }

    /**
     * @param teamId
     * @return
     */
    @PostMapping("/closeTeamStatus")
    @ApiOperation(httpMethod = "GET", value = "")
    public Boolean closeTeamStatus(Long teamId) {
        Boolean tag = false;
        OdsTeam odsTeam = odsTeamService.findById(teamId);
        OdsTeamGoods odsTeamGoods = new OdsTeamGoods();
        odsTeamGoods.setTeamId(teamId);
        //统计该团的全部订单，实际总商品数量和实际总金额
        Map<String, Integer> nod = odsTeamGoodsService.selectCountGoods(odsTeamGoods);
        System.out.println("统计该团的全部订单" + nod);
        if (nod == null || nod.get("goodsNum") == null || nod.get("sumPrice") == null) {
            return true;
        }
        Integer goodsNum = nod.get("goodsNum");
        Integer sumPrice = nod.get("sumPrice");
        //数量满
        if (odsTeam.getTeamNum() > 0 && odsTeam.getTeamNum() <= goodsNum) {
            tag = true;
        }//金额满
        else if (odsTeam.getTeamMoney() > 0 && odsTeam.getTeamMoney() <= sumPrice) {
            tag = true;
        }
        //满团
        if (tag) {
            odsTeam.setTeamStatus((byte) 2);
            odsTeam.setFinishMoney(sumPrice);
            odsTeam.setFinishNum(goodsNum);
            odsTeamService.update(odsTeam);

            //更新订单
            OdsTeamIntent odsTeamIntent = new OdsTeamIntent();
            odsTeamIntent.setTeamId(teamId);
            odsTeamIntent.setIntentStatus((byte) 1);
            odsTeamIntent.setShippingStatus((byte) 1);
            odsTeamIntentService.updateTeamIntent(odsTeamIntent);

        }//判断是否到期，或者是否已经截团。
        else if (System.currentTimeMillis() >= odsTeam.getEndTime().getTime()) {
            odsTeam.setTeamStatus((byte) 4);
            odsTeamService.update(odsTeam);

            //更新订单调用退款模块
            refoundTeam(teamId);
        }
        return tag;
    }

    /**
     * 退款模块
     *
     * @param teamId
     * @return
     */
    @PostMapping("/refoundTeam")
    @ApiOperation(httpMethod = "GET", value = "")
    public Boolean refoundTeam(Long teamId) {
        //查找TeamId下所有已支付的订单
        Example example = new Example(OdsTeamIntent.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("teamId", teamId);
        criteria.andEqualTo("payStatus", 1);
        criteria.andGreaterThan("amountPaid", 0);
        criteria.andCondition("intent_status < 3");
        List<OdsTeamIntent> odsTeamIntentList = odsTeamIntentService.selectByExample(example);
        if (odsTeamIntentList != null && odsTeamIntentList.size() > 0) {
            for (OdsTeamIntent odsTeamIntent : odsTeamIntentList) {
                odsTeamIntent.setTeamId(teamId);
                odsTeamIntent.setIntentStatus((byte) 4);
                odsTeamIntentService.update(odsTeamIntent);
                //退款
                odsTeamIntentController.refoundIntentOrder(odsTeamIntent);
            }
        }
        return true;
    }


    /**
     * 团购月账单，按月统计
     *
     * @param shopId
     * @return
     */
    @GetMapping("/accountTeamIntentMonth")
    @ApiOperation(httpMethod = "GET", value = "记录")
    public Wrapper<PageInfo<Map<String, String>>> accountTeamIntentMonth(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                         @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                         @ApiParam(name = "shopId", value = "该数据记录的POJO") @RequestParam(defaultValue = "0") Long shopId) {
        PageHelper.startPage(page, size);
        List<Map<String, String>> map = odsTeamService.accountTeamIntentMonth(shopId);
        if (map == null) {
            return WrapMapper.error("没有记录或计算错误。");
        }
        PageInfo pageInfo = new PageInfo(map);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 团购账单，当月统计
     *
     * @param shopId
     * @return
     */
    @GetMapping("/accountTeamIntentDay")
    @ApiOperation(httpMethod = "GET", value = "记录")
    public Wrapper<PageInfo<Map<String, String>>> accountTeamIntentDay(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                       @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                       @ApiParam(name = "shopId", value = "该数据记录的POJO") @RequestParam Long shopId) {
        PageHelper.startPage(page, size);
        List<Map<String, String>> map = odsTeamService.accountTeamIntentDay(shopId);
        if (map == null) {
            return WrapMapper.error("没有记录或计算错误。");
        }
        PageInfo pageInfo = new PageInfo(map);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 收益详细表
     */
    @GetMapping("/teamIntentCommission")
    @ApiOperation(httpMethod = "GET", value = "记录")
    public Wrapper<PageInfo<Map<String, String>>> teamIntentCommission(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                       @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                       @ApiParam(name = "shopId", value = "") @RequestParam Long shopId,
                                                                       @ApiParam(name = "checkStatus", value = "0") @RequestParam Byte checkStatus) {
        PageHelper.startPage(page, size);
        List<OdsTeamGoodsDto> list = odsTeamGoodsService.teamIntentCommission(shopId,checkStatus);
        if (list == null) {
            return WrapMapper.error("没有记录或计算错误。");
        }

        PageInfo pageInfo = new PageInfo(list);

        return WrapMapper.ok(pageInfo);
    }

    /**
     * 获取团长总收益和当月收益（已到账）
     * @param shopId
     * @return
     */
    @GetMapping("/teamProfit")
    public Wrapper<Map<String, String>> getTeamProfit(@ApiParam(name = "shopId", value = "该数据记录的POJO") @RequestParam Long shopId) {
        Map<String, String> map = odsTeamService.getTeamProfit(shopId);
        return WrapMapper.ok(map);
    }
}
